import editForm from "../form.vue";
import menuForm from "../menu.vue";
import {
  type Permission,
  addPermission,
  updatePermission,
  deletePermission,
  getPermissionList,
  bindMenu,
  getPermissionGroups
} from "@/api/system";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { DictTag } from "@/components/ReDict";

export function userPermission() {
  const form = reactive<Permission>({
    current: 1,
    size: 20
  });
  const formRef = ref();
  const dataList = ref([]);
  const groupOptions = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1
  });
  const columns: TableColumnList = [
    {
      label: "权限名称",
      prop: "name",
      width: 200
    },
    {
      label: "权限代码",
      prop: "code",
      width: 200
    },
    {
      label: "权限分组",
      prop: "group",
      width: 200
    },
    {
      label: "权限说明",
      prop: "description"
    },
    {
      label: "状态",
      prop: "state",
      width: 80,
      cellRenderer: ({ row, props }) => (
        <DictTag size={props.size} value={row.state} code="State" />
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 250,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    form.size = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.current = val;
    onSearch();
  }

  function onSearch() {
    loading.value = true;
    getPermissionList(form)
      .then(data => {
        dataList.value = data.records;
        pagination.total = data.total;
        pagination.pageSize = data.size;
        pagination.currentPage = data.current;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const resetForm = (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: Permission) {
    addDialog({
      title: `${title}权限`,
      props: {
        formInline: {
          id: row?.id ?? "",
          name: row?.name ?? "",
          code: row?.code ?? "",
          value: row?.description ?? "",
          state: row?.state ?? true,
          group: row?.group ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as Permission;
        function add() {
          addPermission(curData)
            .then(() => {
              message("权限新增成功", {
                type: "success"
              });
              onSearch(); // 刷新表格数据
              loadPermissionGroups();
              done(); // 关闭弹框
            })
            .catch(err => {
              message(`权限新增失败:${err.message}`, {
                type: "error"
              });
            });
        }
        function update() {
          updatePermission(curData)
            .then(() => {
              message("权限更新成功", { type: "success" });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(err => {
              message(`权限更新失败:${err}`, { type: "error" });
            });
        }
        FormRef.validate((valid: boolean) => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              add();
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              update();
            }
          }
        });
      }
    });
  }

  function openMenuDialog(permissionId: string, name: string) {
    addDialog({
      title: `分配菜单-${name}`,
      props: {
        formInline: {
          permissionId: permissionId
        }
      },
      width: "30%",
      draggable: true,
      fullscreenIcon: true,
      destroyOnClose: true,
      contentRenderer: () => h(menuForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline;

        const submit = () => {
          bindMenu(curData.permissionId, curData.menu)
            .then(() => {
              message("菜单分配成功", { type: "success" });
              done(); // 关闭弹框
            })
            .catch(err => {
              message(`菜单分配失败:${err}`, { type: "error" });
            });
        };
        submit();
      }
    });
  }

  function handleDelete(row: Permission) {
    deletePermission(row.id)
      .then(() => {
        message("权限删除成功", { type: "success" });
        onSearch();
      })
      .catch(err => {
        message(`权限删除失败:${err}`, { type: "error" });
      });
  }

  function loadPermissionGroups() {
    getPermissionGroups().then(res => {
      groupOptions.value = res;
    });
  }

  onMounted(() => {
    onSearch();
    loadPermissionGroups();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    groupOptions,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    openMenuDialog,
    handleSizeChange,
    handleCurrentChange
  };
}
